<?php
/*
 * @Description  : 壁纸图片管理
 * @Author       : https://github.com/skyselang
 * @Date         : 2020-05-06
 * @LastEditTime : 2020-12-25
 */

namespace app\admin\service;

use app\common\cache\ImgCache;
use Exception;
use think\facade\Config;
use think\facade\Db;

class ImgService
{
    const TABLE = "img";

    /**
     * 查询条件
     *
     * @param array   $data   参数
     * 
     * @return array 
     */
    private static function map(array $data)
    {
        $map = [];
        //名字、类别、标题做模糊查询
        if (!empty($data['category_ids'])) {
            foreach ($data['category_ids'] as $key => $value) {
                $map[] = Db::raw("FIND_IN_SET('{$value}',category_ids)");
            }
        }
        if ($data['name']) {
            $map[] = ["name", 'like', "%{$data['name']}%"];
        }
        if ($data['title']) {
            $map[] = ["title", 'like', "%{$data['title']}%"];
        }
        if ($data['source_name']) {
            $map[] = ["source_name", '=', "{$data['source_name']}"];
        }
        if ($data['status']) {
            $map[] = ["status", '=', "{$data['status']}"];
        }
        if ($data['create_time_start'] && $data['create_time_end']) {
            $map[] = [
                'create_time', '>=', "{$data['create_time_start']}"
            ];
            $map[] = [
                'create_time', '<=', "{$data['create_time_end']}"
            ];
        }
        return $map;
    }

    /**
     * 壁纸图片列表
     *
     * @param array   $param   参数
     * @param integer $page    页数
     * @param integer $limit   数量
     * @param string  $field   字段
     * 
     * @return array 
     */
    public static function findList($param, $pp = 1, $num = 10,  $field = 'i.*')
    {
        //查询条件
        $order = ['i.sort' => 'desc', 'i.img_id' => 'desc'];
        $map = self::map($param);
        $count = Db::name(self::TABLE)->where($map)->count();
        //计算pp
        $pp = ceil($count / $num) < $pp ? ceil($count / $num) : $pp;
        //查询数据
        $list = Db::name(self::TABLE)
            ->alias('i')
            ->where($map)
            ->order($order)
            ->page($pp, $num)
            ->field(Db::raw($field . ",GROUP_CONCAT(j.category_id) AS category_ids"))
            ->join('bz_img_category_join j', 'j.img_id = i.img_id', 'left')
            ->group('i.img_id')
            ->select();
        return [
            'list' => $list,
            'count' => $count,
            'pp' => $pp
        ];
    }

    /**
     * 壁纸图片添加
     *
     * @param array $param 壁纸图片数据
     * 
     * @return void
     */
    public static function add($param)
    {
        Db::startTrans();
        try {
            $category_ids = $param['category_ids'];
            unset($param['category_ids']);
            $param['create_time'] = date('Y-m-d H:i:s');
            $param['update_time'] = date('Y-m-d H:i:s');
            $img_id = Db::name(self::TABLE)->insertGetId($param);
            if (!$img_id) throw new Exception("mysql存储异常！");
            $param['img_id'] = $img_id;
            //存储缓存
            $result = ImgCache::set($img_id, $param, 0);
            if ($result === false) throw new Exception("redis存储异常！");
            $joinAdd = [];
            foreach ($category_ids as $category_id) {
                $joinAdd[] = [
                    'img_id' => $img_id,
                    'category_id' => $category_id
                ];
            }
            $result = Db::name("img_category_jojn")->insertAll($joinAdd);
            if (!$result) throw new Exception("mysql存储异常！");
            Db::commit();
            return success([
                'img_id' => $img_id
            ]);
        } catch (Exception $e) {
            Db::rollback();
            return error($e->getMessage());
        }
    }

    /**
     * 壁纸图片修改
     *
     * @param array $param 壁纸图片数据
     * 
     * @return void
     */
    public static function edit($param)
    {
        Db::startTrans();
        try {
            $param['update_time'] = date('Y-m-d H:i:s');
            $y_imagePath = $param['y_imagePath'];
            $img_id = $param['img_id'];
            unset($param['y_imagePath']);
            if (!Db::name(self::TABLE)->where("img_id", $img_id)->update($param)) throw new Exception("更新异常！");
            //存储缓存
            $result = ImgCache::set($img_id, $param, 0, true);
            if ($result === false) throw new Exception("redis更新异常！");
            //有新图上传则原图、缩略图删除
            if (isset($param['set_path'])) {
                $path = Config::get("filesystem.disks.bizhi.root");
                $filePath = str_replace("\\", "/", $path . "/" . $y_imagePath);
                if (is_file($filePath)) {
                    unlink($filePath);
                }
                $pathList = explode("/", $y_imagePath);
                $last = end($pathList);
                $sFilePath = str_replace("\\", "/", $path . "/" . str_replace($last, "s_" . $last, $y_imagePath));
                if (is_file($sFilePath)) {
                    unlink($sFilePath);
                }
            }
            Db::commit();
            return success([
                'img_id' => $img_id
            ]);
        } catch (\Exception $e) {
            //事务回滚加删除文件
            Db::rollback();
            if (isset($param['set_path'])) {
                $path = Config::get("filesystem.disks.bizhi.root");
                $filePath = str_replace("\\", "/", $path . "/" . $param['set_path']);
                if (is_file($filePath)) unlink($filePath);
            }
            return error($e->getMessage());
        }
    }
}
